package com.person.jc.web.security;

import java.util.List;
import java.util.Map;

import com.jfinal.core.Controller;
import com.jfinal.plugin.activerecord.Record;
import com.person.jc.common.Constants;
import com.person.jc.entity.TsUser;
import com.person.jc.service.security.TsRoleService;
import com.person.jc.service.security.TsUserService;
import com.person.jc.utils.MyMD5;
import com.person.jc.utils.Servlets;
import com.person.jc.utils.Utils;

public class TsUserController extends Controller {
	
	public void init() {
	    setAttr("menuId", getPara("menuId"));
		render("main.jsp");
	}
	
	public void list() {
	    Map<String,Object> map = Servlets.getParametersStartingWith(getRequest(), "p_");
	    List<Record> list = TsUserService.me.getList(map);
		setAttr("list", list);
		render("list.jsp");
	}
	
	public void edit() {
		Map<String,Object> map = Servlets.getParametersStartingWith(getRequest(), "p_");
		String view = getPara("view");
		if (Utils.isNotEmpty(String.valueOf(map.get("userId")))){
			List<Record> list = TsUserService.me.getList(map);
			if(list.size() != 0){
				setAttr("user", list.get(0));
			}
		    setAttr("view", view);
		}
		List<?> roleList = TsRoleService.me.getUserRoleList(String.valueOf(map.get("userId"))); 
		setAttr("roleList", roleList);
		render("edit.jsp");
	}
	
	public void save() {
		String res = "success";
		Map<String,Object> map = Servlets.getParametersStartingWith(getRequest(), "p_");
		String userId = String.valueOf(map.get("userId"));
		try{
			if(Utils.isEmpty(String.valueOf(map.get("old_userId")))){
				TsUserService.me.save(map);
			}else{
				TsUser tsUser = (TsUser)getSessionAttr(Constants.LOGIN_USER);
				if(!tsUser.getPassword().equals(String.valueOf(map.get("password")))){
					map.put("password", MyMD5.myMD5(String.valueOf(map.get("password"))));					
				}
				TsUserService.me.update(map);
			}
			TsUserService.me.delUserRole(userId);
			TsUserService.me.saveUserRole(map);
        }catch(Exception e){
        	e.printStackTrace();
        	res = "error";
        }
        renderText(res);
	}
	
	public void updateStatus() {
		String res = "success" ;
		String ids = getPara("ids");
		String status = getPara("status");
		try{
			if(Utils.isNotEmpty(ids)){
				TsUserService.me.updateStatus(ids,status);
			}
		}catch(Exception e){
			res = "error";
			e.printStackTrace();
		}
		renderText(res);
	}
	
	public void checkName(){
		String userId = getPara("userId");
		long i = TsUserService.me.getNameCount(userId); 
		renderText(i == 0 ? "SUCCESS" : "ERROR");
	}
	
}
